import API from "@/common/api.js";
const qqMapKey = "HJ5BZ-CZN6U-E4FVZ-2P43D-AYPHV-EEBIU";

const statusBarHeight = uni.getSystemInfoSync().statusBarHeight + "px"; //屏幕顶部间隔
const themeColor = "#1dbc9a";
let requestLodingType = "mask"; //api请求显示的loding类型，mask不可点击，none可点击，一切false类则不显示loding
const appLogo = "https://wx.qlogo.cn/mmhead/Q3auHgzwzM6H53QCbwcy2X2MbxqqRaDCPuUU92bREJaIRria8s4ib4WA/0";

function getThemeColor() {
  return themeColor;
}
function getAppLogo() {
  return appLogo;
}

function getStatusBarHeight() {
  return statusBarHeight;
}

Date.prototype.format = function (format) {
  var args = {
    "M+": this.getMonth() + 1,
    "d+": this.getDate(),
    "h+": this.getHours(),
    "m+": this.getMinutes(),
    "s+": this.getSeconds(),
    "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
    S: this.getMilliseconds(),
  };
  if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var i in args) {
    var n = args[i];
    if (new RegExp("(" + i + ")").test(format))
      format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? n : ("00" + n).substr(("" + n).length));
  }
  return format;
};

function showToast(title, icon = "none", duration = 2000) {
  uni.showToast({
    title,
    icon,
    duration,
  });
}

function showErrorToast(title) {
  uni.showToast({
    title: title,
    icon: "error",
    duration: 3000,
  });
}

function showSuccessToast(title, navigateBack = false) {
  uni.showToast({
    title: title,
    icon: "success",
    duration: 1000,
  });
  if (navigateBack) {
    setTimeout(() => {
      uni.navigateBack({
        delta: 1,
      });
    }, 1000);
  }
}

function returnShareObj() {
  return {
    title: "海权康护",
    path: "/pages/index/index",
  };
}
function cleanLoginInfo() {
  showToast("登录过期，即将自动重新登录");
  uni.removeStorageSync("token");
  setTimeout(() => {
    uni.reLaunch({
      url: "/pages/index/index",
    });
  }, 1500);
}

function showModal(msg, success) {
  uni.showModal({
    title: "提示",
    content: msg,
    showCancel: false,
    success: function (res) {
      if (success) {
        success(res);
      }
    },
  });
}

function uploadPicture(path, name = "图片", success) {
  let token = uni.getStorageSync("token");
  uni.showLoading({
    mask: true,
    title: "请稍候",
  });
  uni.uploadFile({
    url: API.baseUrl + API.urlPrefix + "doctor/uploadFile", // 后端api接口
    filePath: path, // uni.chooseImage函数调用后获取的本地文件路劲
    name: "file", //后端通过'file'获取上传的文件对象
    header: {
      "Content-Type": "multipart/form-data",
      Authorization: "Bearer " + token,
    },
    success: (res) => {
      uni.hideLoading();
      let data = JSON.parse(res.data);
      if (data.code == 200) {
        if (success) {
          success(data);
        }
      } else if (data.code == 401) {
        showErrorToast(res.message);
        cleanLoginInfo();
      } else {
        showErrorToast(name + "上传失败");
      }
    },
    fail: (res) => {
      uni.hideLoading();
      showErrorToast(name + "上传失败");
    },
  });
}
//从对象中选择一些属性组合成新对象
function pickObj(obj, arr) {
  return arr.reduce((item, val) => (val in obj && (item[val] = obj[val]), item), {});
}

//跳转路由,url为false类默认返回上一页
function goUrl(url) {
  if (url) {
    uni.navigateTo({
      url,
    });
  } else {
    uni.navigateBack({
      delta: 1,
    });
  }
}
//毫秒转文字
function getTimeStr(time) {
  if (typeof time == "string") {
    time = time.replace(/-/g, "/");
  }
  time = new Date(time);
  let month = time.getMonth() + 1,
    date = time.getDate(),
    hour = time.getHours(),
    minutes = time.getMinutes(),
    seconds = time.getSeconds();
  return (
    time.getFullYear() +
    "-" +
    (month > 9 ? month : "0" + month) +
    "-" +
    (date > 9 ? date : "0" + date) +
    " " +
    (hour > 9 ? hour : "0" + hour) +
    ":" +
    (minutes > 9 ? minutes : "0" + minutes) +
    ":" +
    (seconds > 9 ? seconds : "0" + seconds)
  );
}
//返回并刷新上一页  上一页刷新方法请定义为refreshByBack(),接受一个参数对象data
function backToRefreshPrevPage(prevPage, data = null) {
  if (prevPage) {
    let pages = getCurrentPages();
    pages.some((item, index) => {
      let ind = item.route.indexOf(prevPage);
      if (ind > -1) {
        if (index == pages.length - 1) {
          item.$vm.refreshByBack(data);
          return true;
        } else if (index == pages.length - 2) {
          goUrl(0);
          item.$vm.refreshByBack(data);
          return true;
        }
      }
    });
  }
}
//拨打电话
function makePhoneCall(phoneNumber) {
  if (phoneNumber) {
    uni.makePhoneCall({
      phoneNumber,
    });
  }
}
//计算年龄
function getAgeBirth(strBirthday) {
  let returnAge;
  const strBirthdayArr = strBirthday.split("-");
  const birthYear = parseInt(strBirthdayArr[0]);
  const birthMonth =parseInt(strBirthdayArr[1]);
  const birthDay = parseInt(strBirthdayArr[2]);
  

  const d = new Date();
  const nowYear = d.getFullYear();
  const nowMonth = d.getMonth() + 1;
  const nowDay = d.getDate();

  if (nowYear === birthYear) {
    returnAge = 0; // 同年 则为0岁
  } else {
    const ageDiff = nowYear - birthYear; // 年之差
    if (ageDiff > 0) {
      if (nowMonth === birthMonth) {
        const dayDiff = nowDay - birthDay; // 日之差
        if (dayDiff < 0) {
          returnAge = ageDiff - 1;
        } else {
          returnAge = ageDiff;
        }
      } else {
        const monthDiff = nowMonth - birthMonth; // 月之差
        if (monthDiff < 0) {
          returnAge = ageDiff - 1;
        } else {
          returnAge = ageDiff;
        }
      }
    } else {
      returnAge = "0"; // 返回-1 表示出生日期输入错误 晚于今天
    }
  }
  return returnAge; // 返回周岁年龄
}
module.exports = {
  showToast,
  showErrorToast,
  showSuccessToast,
  cleanLoginInfo,
  returnShareObj,
  showModal,
  uploadPicture,
  pickObj,
  qqMapKey,
  requestLodingType,
  goUrl,
  getStatusBarHeight,
  getThemeColor,
  backToRefreshPrevPage,
  makePhoneCall,
  getAgeBirth,
  getAppLogo,
  getTimeStr,
};
